package com.heima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

//全局异常处理器
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionInSaveHandler(SQLIntegrityConstraintViolationException ex){
        log.info("捕获异常");
        log.info(ex.getMessage());
        if(ex.getMessage().contains("Duplicate entry")){
            return R.error("用户名已存在请重新输入");
        }
        return R.error("未知错误，添加失败");
    }
}
